package cn.easybuy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.easybuy.entity.Category;
import cn.easybuy.entity.MyOrder;
import cn.easybuy.entity.News;
import cn.easybuy.entity.Product;
import cn.easybuy.service.BuyCarService;
import cn.easybuy.service.impl.BuyCarServiceImpl;
import cn.easybuy.service.impl.GoodServiceImpl;

import com.alibaba.fastjson.JSON;

@WebServlet("/goodsServlet")
public class goodsServlet extends HttpServlet {
	public static Integer[] listId = new Integer[5];
	public static int index = 0;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		req.setCharacterEncoding("utf-8");
		PrintWriter out = resp.getWriter();
		GoodServiceImpl gsi = new GoodServiceImpl();
		BuyCarService buyCarService=new BuyCarServiceImpl();
		String opr = req.getParameter("opr");
		HttpSession session = req.getSession();
		if ("leftlist".equals(opr)) {
			List<Category> list = null;
			try {
				list = gsi.findLevel1();
				for (Category c : list) {
					out.print("<li id="
							+ c.getId()
							+ "><div class=\"fj\"><span class=\"n_img\"><span></span><img src=\"images/"
							+ c.getIcon()
							+ "\" /></span><span class=\"fl\">"
							+ c.getName()
							+ "</span></div><div class=\"zj\"><div class=\"zj_l\"></div><div class=\"zj_r\"><a href=\"#\"><img src=\"images/n_img1.jpg\" width=\"236\" height=\"200\" /></a><a href=\"#\"><img src=\"images/n_img2.jpg\" width=\"236\" height=\"200\" /></a></div></div></li>");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if ("findLevel2".equals(opr)) {
			int id = 0;
			if (!req.getParameter("id").equals("undefined")) {
				id = Integer.parseInt(req.getParameter("id"));
			} else {
				out.print("<div class=\"zj_l_c\"><h2 class=\"h22\" >暂无数据</h2></div>");
				return;
			}
			List<Category> list = null;
			try {
				list = gsi.findLevel2(id);
				if (list.size() == 0) {
					out.print("<div class=\"zj_l_c\"><h2 class=\"h22\" >暂无数据</h2></div>");
				} else {
					int i =0;
					int i2 = 0;
					for(Category c : list){
						if(i2==0){
							out.print(c.getId());
							i2++;
						}else{
							out.print(":"+c.getId());
						}
					}
					out.print(",");
					for (Category c : list) {
						out.print("<div class=\"zj_l_c\" id=\"id"+(i++)+"\"><h2>" + c.getName() + "</h2></div>");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if ("findLevel3".equals(opr)) {
			int id = 0;
			if (!req.getParameter("id").equals("undefined")) {
				id = Integer.parseInt(req.getParameter("id"));
			} else {
				out.print("<a href=\"\">暂无数据</a>|");
				return;
			}
			List<Category> list = null;
			try {
				list = gsi.findLevel3(id);
				if (list.size() == 0) {
					out.print("<a href=\"\">暂无数据</a>|");
				} else {
					for (Category c : list) {
						out.print("<a href=\"searchServlet?opr=chuan&search="
								+ c.getName() + "\">" + c.getName() + "</a>|");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if ("NewsTop5".equals(opr)) {
			try {
				List<News> list = gsi.getTop5list();
				for (News n : list) {
					out.print("<li><span>[ 公告  ]</span><a href=\"#\">"
							+ n.getTitle() + "</a></li>");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if ("hostlist".equals(opr)) {
			try {
				List<Product> list = gsi.gethostlist();
				for (Product p : list) {
					out.print("<li class=\"featureBox\"><div class=\"box\"><div class=\"h_icon\"><img src=\"images/hot.png\" width=\"50\" height=\"50\" /></div><div class=\"imgbg\"><a href=\"goodsServlet?opr=xq&id="
							+ p.getId()
							+ "\"><img src=\"images/"
							+ p.getFileName()
							+ "\" width=\"160\" height=\"136\" /></a></div><div class=\"name\"><a href=\"goodsServlet?opr=xq&id="
							+ p.getId()
							+ "\"><h2>"
							+ p.getName()
							+ "</h2>"
							+ p.getDescription()
							+ "</a></div><div class=\"price\"><font>￥<span>"
							+ p.getPrice()
							+ "</span></font> &nbsp; "
							+ p.getScore() + "R</div></div></li>");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if ("leilist".equals(opr)) {
			try {
				List<Category> list = gsi.findLevel1();
				out.print(JSON.toJSON(list));
				/*
				 * for(Category c: list){ i++;
				 * out.print("<div id="+c.getId()+" onload=getLevel3("
				 * +c.getId()+
				 * ")><div class=\"i_t mar_10\"><span class=\"floor_num\">"
				 * +i+"F</span><span class=\"fl\">"+c.getName()+
				 * "</span><span class=\"i_mores fr\"></span></div><div class=\"content\"><div class=\"fresh_left\"><div class=\"fre_ban\"><div id=\"imgPlay1\"><ul class=\"imgs\" id=\"actor1\"><li><a href=\"#\"><img src=\"images/fre_r.jpg\" width=\"211\" height=\"286\" /></a></li><li><a href=\"#\"><img src=\"images/fre_r.jpg\" width=\"211\" height=\"286\" /></a></li><li><a href=\"#\"><img src=\"images/fre_r.jpg\" width=\"211\" height=\"286\" /></a></li></ul><div class=\"prevf\">閿熸枻鎷蜂竴閿熸枻鎷�/div><div class=\"nextf\">閿熸枻鎷蜂竴閿熸枻鎷�/div></div></div><div class=\"fresh_txt\"><div class=\"fresh_txt_c\"></div></div></div><div class=\"fresh_mid\"><ul><li><div class=\"name\"><a href=\"#\">閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷峰懗  閿熸枻鎷烽敓鏂ゆ嫹閿熺粸锟�a></div><div class=\"price\">font>閿熸枻鎷�span>198.00</span></font> &nbsp; 26R</div><div class=\"img\"><a href=\"#\"><img src=\"images/fre_1.jpg\" width=\"185\" height=\"155\" /></a></div></li></ul></div></div>"
				 * ); }
				 */
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else if ("getLevel3".equals(opr)) {
			try {
				int id3 = 0;
				if (!req.getParameter("id3").equals("undefined")) {
					id3 = Integer.parseInt(req.getParameter("id3"));
				}
				List<Category> list = gsi.getLevel3list(id3);
				for (Category c : list) {
					out.print("<a href=\"searchServlet?opr=chuan&search="
							+ c.getName() + "\">" + c.getName()
							+ "</a>&nbsp; &nbsp; &nbsp;");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else if ("getLevel1commodity".equals(opr)) {
			try {
				int id4 = 0;
				if (!req.getParameter("id4").equals("undefined")) {
					id4 = Integer.parseInt(req.getParameter("id4"));
				}
				List<Product> list = gsi.getLevel1commodity(id4);
				if (list.size() == 0) {
					out.print("<li><a>閿熸枻鎷烽敓鏂ゆ嫹閿燂拷/a></li>");
					out.print(",");
					out.print("<li><div class=\"name\"><a>閿熸枻鎷烽敓鏂ゆ嫹閿燂拷/a></div><div class=\"price\"><font><span></span></font> &nbsp;</div><div class=\"img\"><a href=\"#\"></a></div></li>");
				} else {
					for (Product p : list) {
						out.print("<li><a href=\"goodsServlet?opr=xq&id="
								+ p.getId() + "\"><img src=\"images/"
								+ p.getFileName()
								+ "\" width=\"211\" height=\"286\" /></a></li>");
					}
					out.print(",");
					for (Product p : list) {
						out.print("<li><div class=\"name\"><a href=\"goodsServlet?opr=xq&id="
								+ p.getId()
								+ "\">"
								+ p.getName()
								+ "</a></div><div class=\"price\"><font>￥<span>"
								+ p.getPrice()
								+ "</span></font> &nbsp; "
								+ p.getScore()
								+ "R</div><div class=\"img\"><a href=\"goodsServlet?opr=xq&id="
								+ p.getId()
								+ "\"><img src=\"images/"
								+ p.getFileName()
								+ "\" width=\"185\" height=\"155\" /></a></div></li>");
					}
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("xq".equals(opr)) {
			int id = 0;
			if (!req.getParameter("id").equals("undefined")) {
				id = Integer.parseInt(req.getParameter("id"));
			}
			try {
				List<Product> list = gsi.guige(id);
				String[] gg = null;
				String[] ys = null;
				String gg1 = "";
				String ys1 = "";
				int in = 0;
				int in2 = 0;
				if (list != null) {
					for (Product pr : list) {
						if (pr.getSpecification() != null && pr.getSpecification() != "") {
							if (in == 0) {
								gg1 += pr.getSpecification();
								in++;
							} else {
								gg1 += "," + pr.getSpecification();
							}
						}
					}
					for (Product pr : list) {
						if (pr.getColour() != null && pr.getColour() != "") {
							if (in2 == 0) {
								ys1 += pr.getColour();
								in2++;
							} else {
								ys1 += "," + pr.getColour();
							}
						}

					}
					gg = gg1.split(",");
					ys = ys1.split(",");
					req.setAttribute("gg", gg);
					req.setAttribute("ys", ys);
					req.setAttribute("id", id);
				}

				/*
				 * List<Product> list = gsi.commodity(id); Product p = new
				 * Product(); String lv1 = null; String lv2 = null; String lv3 =
				 * null; String[] gg = null; String[] ys = null; for (Product pr
				 * : list) { p.setId(pr.getId()); p.setName(pr.getName());
				 * p.setDescription(pr.getDescription());
				 * p.setPrice(pr.getPrice()); p.setStock(pr.getStock()); lv1 =
				 * gsi.LV1(pr.getCategoryLevel1()); lv2 =
				 * gsi.LV2(pr.getCategoryLevel2()); lv3 =
				 * gsi.Lv3(pr.getCategoryLevel3());
				 * p.setFileName(pr.getFileName());
				 * p.setIsDelete(pr.getIsDelete()); p.setScore(pr.getScore());
				 * gg = pr.getSpecification().split(","); ys =
				 * pr.getColour().split(","); } req.setAttribute("p", p);
				 * req.setAttribute("lv1", lv1); req.setAttribute("lv2", lv2);
				 * req.setAttribute("lv3", lv3); req.setAttribute("gg", gg);
				 * req.setAttribute("ys", ys);
				 */
				if (index == 5) {
					index = 0;
				}
				boolean bool = true;
				for (int i = 0; i < listId.length; i++) {
					if (listId[i] == null) {
						bool = false;
					}
				}
				boolean flag = true;
				for (int i = 0; i < listId.length; i++) {
					if (listId[i] != null) {
						if (listId[i] == id) {
							flag = false;
						}
					}
				}
				if (flag == true) {
					if (bool == false) {
						for (int i = 0; i < listId.length; i++) {
							if (listId[i] == null) {
								listId[i] = id;
								index++;
								break;
							}
						}
					} else {
						listId[index] = id;
						index++;
					}
				}
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < listId.length; i++) {
					if (listId[i] != null) {
						sb.append(listId[i] + ",");
					}
				}
				Cookie cookie = new Cookie("id", sb.toString().substring(0,
						(sb.toString().length() - 1)));
				resp.addCookie(cookie);
			} catch (Exception e) {
				e.printStackTrace();
			}
			req.getRequestDispatcher("Product.jsp").forward(req, resp);
		} else if ("add".equals(opr)) {
			List<MyOrder> carList = null;
			int id = Integer.parseInt(req.getParameter("id"));
			int type_id = Integer.parseInt(req.getParameter("typeid"));
			float price = Float.parseFloat(req.getParameter("price"));
			int nums = Integer.parseInt(req.getParameter("nums"));
			float cost = price * nums;
			if ((List<MyOrder>) session.getAttribute("carList1") == null) {
				carList = new ArrayList<MyOrder>();
			} else {
				carList = (List<MyOrder>) session.getAttribute("carList1");
				for (MyOrder m : carList) {
					if(m.getType_id()==type_id){
						nums+=m.getQuantity();
						cost+=m.getCost();
						carList.remove(m);
						break;
					}
				}
			}
			MyOrder m = new MyOrder();
			m.setProductId(id);
			m.setQuantity(nums);
			m.setCost(cost);
			m.setProductName(req.getParameter("name"));
			m.setFileName(req.getParameter("filename"));
			m.setSpecification(req.getParameter("gg"));
			m.setColour(req.getParameter("ys"));
			m.setType_id(type_id);
			m.setPrice(price);
			carList.add(m);
			session.setAttribute("carList1", carList);
			
			String userName = (String) session.getAttribute("userName");
			if (userName != null) {
				List<MyOrder> myOrderlist=(List<MyOrder>) session.getAttribute("carList1");
				List<MyOrder> buyCarlist=(List<MyOrder>) session.getAttribute("buyCarlist");
				if(myOrderlist!=null){
					int carid=-1;
				for (MyOrder myOrder : myOrderlist) {
					for (MyOrder myOrder1 : buyCarlist) {
						if(myOrder.getType_id()==myOrder1.getType_id()){
							int shu=myOrder.getQuantity();
							int shu1=myOrder1.getQuantity();
							float price1=myOrder.getPrice();
							myOrder.setQuantity(shu+shu1);
							myOrder.setCost(myOrder.getQuantity()*price1);
							carid=myOrder1.getId();
							myOrder.setDelproductId(carid);
						}
					}
					myOrder.setLoginName((String)session.getAttribute("userName"));
				}
				session.setAttribute("carList1", null);
				try {
					int falg=buyCarService.setBuyCar(myOrderlist);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
			}else{
				
			}
			
			out.print(JSON.toJSON(carList));		
		}else if("xq2".equals(opr)){
			int pid = 0;
			if (!req.getParameter("pid").equals("undefined")) {
				pid = Integer.parseInt(req.getParameter("pid"));
			}
			String guige = req.getParameter("guige");
			String color = req.getParameter("color");
			try {
				List<Product> list = gsi.commodity(guige, color, pid);
				if(list!=null){
					for(Product p: list){
						out.print(p.getId());
						out.print(",");
						out.print(p.getName());
						out.print(",");
						out.print(gsi.LV1(p.getCategoryLevel1()));
						out.print(",");
						out.print(gsi.LV2(p.getCategoryLevel2()));
						out.print(",");
						out.print(gsi.Lv3(p.getCategoryLevel3()));
						out.print(",");
						out.print(p.getSpecificationid());
						out.print(",");
						out.print(p.getTypeid());
						out.print(",");
						out.print(p.getPrice());
						out.print(",");
						out.print(p.getStock());
						out.print(",");
						out.print(p.getFileName());
						out.print(",");
						out.print(p.getIsDelete());
						out.print(",");
						out.print(p.getScore());
						out.print(",");
						out.print(p.getState());
						out.print(",");
						out.print(p.getDescription());
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if ("selectCar".equals(opr)) {
			List<MyOrder> list = (List<MyOrder>) session
					.getAttribute("carList1");
			int i = 0;
			float price2 = 0;
			if (list == null) {
				i = 0;
				price2 = 0;
			} else {
				for (MyOrder m : list) {
					i++;
					out.print("<li><div class='img'><a href='#'><img src='images/"
							+ m.getFileName()
							+ "' width='58' height='58' /></a></div><div class='name'><a href='#'>"
							+ m.getProductName()
							+ "</a></div><div class='price'><font color='#ff4e00'>￥"
							+ m.getCost()
							+ "</font> X"
							+ m.getQuantity()
							+ "</div></li>");
					price2 += m.getCost();
				}
			}
			out.print(",");
			out.print("购物车[ <span class=\"numi\" id="+i+">" + i + "</span> ]");
			out.print(",");
			out.print("共计&nbsp; <font color='#ff4e00'>￥</font><span>" + price2
					+ "</span>");
			out.flush();
			out.close();
		}
	}

}
